package com.share.shareplatform.sharegoods.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.share.shareplatform.common.state.GoodsKind;
import com.share.shareplatform.pojo.*;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.sharegoods.fallback.CustomerBlockHandler;
import com.share.shareplatform.sharegoods.service.BrandService;
import com.share.shareplatform.sharegoods.service.GoodsService;
import com.share.shareplatform.sharegoods.service.ShopService;
import com.share.shareplatform.sharegoods.service.TypeService;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
@RefreshScope
public class GoodsController {


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private TypeService typeService;

    @Value("${server.port}")
    private String port;

    @ApiOperation(value="获取所有商品信息，分页查询",notes = "必需字段：pageIndex(起始页)，pageSize(每页大小)")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "第几页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页的大小", required = true, dataType = "Integer")
    })*/
    @GetMapping("/page/{pageIndex}/{pageSize}")
    @PermitAll
    @SentinelResource(value ="GoodsController.getUserPage")
    public Result getUserPage(@PathVariable("pageIndex") Integer pageIndex, @PathVariable("pageSize") Integer pageSize){
        if(pageIndex<0||pageSize<0){
            return Result.getInstance(505,"页码有误").put("list",null);
        }
        List<Goods> list=goodsService.findPage(pageIndex,pageSize);
        return Result.getInstance(200,"success").put("list",list);
    }


    /*
     *
     * 判断是否是管理员，如果是管理员，只需要
     * 判断店铺是否存在
     *
     * 如果是店主，还要判断店主是否拥有店铺
     *
     * */
    @ApiOperation(value="添加",notes = "必需字段：name,place,price,number\n可选字段：brandId,typeId,introduce\n额外说明：如果是超级管理员，则必需指定shopId字段")
    @PostMapping
    @PreAuthorize("hasAuthority('goodsSuper')")
    @SentinelResource(value ="GoodsController.addOne")
    public Result addOne(@RequestBody  Goods goods) throws Exception {

        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId = AuthorityUtil.getUserId();
            Shop shop = shopService.findOneByUserId(userId);
            if(shop==null){
                throw new Exception("您不是商家，无法添加商品");
            }

            goods.setShopId(shop.getId());
        }else{
            if(goods.getShopId()==null){
                throw new Exception("请指定商品所属店铺");
            }
            Shop shop = shopService.findOneByUserId(goods.getShopId());
            if(shop==null){
                throw new Exception("该店铺不存在");
            }
            goods.setShopId(shop.getId());
        }

        //初始化商品
        Goods.setInit(goods);

        Long flag = goodsService.addOne(goods);
        if(flag==0){
            return Result.getInstance(505,"添加失败");
        }
        return Result.getInstance(200,"添加成功");
    }

    @ApiOperation(value="修改",notes = "可选字段：name,place,price,number,brandId,typeId,introduce")
    @PutMapping
    @PreAuthorize("hasAuthority('goodsUpdate')")
    @SentinelResource(value ="GoodsController.updateOne")
    public Result updateOne(@RequestBody @Validated Goods goods) throws Exception {
        if(goods.getId()==null){
            throw new LogicException("请输入商品Id");
        }
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId = AuthorityUtil.getUserId();
            Shop shop = shopService.findOneByUserId(userId);

            if(shop==null){
                throw new LogicException("您不是商家，无法修改商品");
            }
            goods.setShopId(shop.getId());
        }else{
            if(goods.getShopId()==null){
                throw new LogicException("请指定商品所属店铺");
            }
            Shop shop = shopService.findOneById(goods.getShopId());
            if(shop==null){
                throw new LogicException("该店铺不存在");
            }
            goods.setShopId(shop.getId());
        }
        Goods oldGoods = goodsService.findOneById(goods.getId());
        if(oldGoods==null){
            throw new LogicException("该商品不存在");
        }
        if(oldGoods.getShopId()!=goods.getShopId()){
            throw new LogicException("该商品不属于这个店铺");
        }
        Goods.update(oldGoods,goods);
        Integer flag = goodsService.updateOne(oldGoods);
        if(flag==0){
            throw new LogicException("修改失败，请联系管理员");
        }
        return Result.getInstance(200,"success");
    }



    @ApiOperation(value="删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('goodsDelete')")
    @SentinelResource(value ="GoodsController.deleteOneById")
    public Result deleteOneById(@PathVariable("id") Long id) throws LogicException {

        Integer flag = goodsService.deleteOneById(id);
        if(flag==0){
            throw new LogicException("删除失败");
        }

        return Result.getInstance(200,"删除成功");
    }

    @ApiOperation(value="批量删除",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    @DeleteMapping("/all/{ids}")
    @PreAuthorize("hasAuthority('goodsDelete')")
    @SentinelResource(value ="GoodsController.updateOne")
    public Result deleteAllByIds(@PathVariable("ids") String ids) throws LogicException {
        String[] stringIds=ids.split("-");

        ArrayList<Long> arrayList=new ArrayList<>();
        for(String id:stringIds){
            arrayList.add(Long.parseLong(id));
        }
        Integer flag = goodsService.deleteAllByIds(arrayList);
        if(flag==0){
            throw new LogicException("删除失败");
        }
        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="查询，按id")
    @GetMapping("/{id}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findOneById")
    public Result findOneById(@PathVariable("id") Long id){

        Goods goods=goodsService.findOneById(id);

        if(goods!=null){
            return Result.getInstance(200,"success").put("goods",goods);
        }
        else{
            return Result.getInstance(505,"not found");
        }
    }



    @ApiOperation(value = "批量查询指定商品,以形式map返回")
    @GetMapping("/all/map/{ids}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllByIdAsMap")
    Result findAllByIdAsMap(@PathVariable("ids") String ids)  {
        Map<Long,Goods> map= goodsService.findAllByIdAsMap(ids);

        return Result.getInstance(200,"success").put("map",map);
    }


    @ApiOperation(value="查询已登录用户上架的商品")
    @GetMapping("/all/token/userId")
    @PreAuthorize("hasAuthority('goodsFind')")
    @SentinelResource(value ="GoodsController.findOneByUserId")
    public Result findOneByUserId(){
        Long userId = AuthorityUtil.getUserId();
        Shop shop = shopService.findOneByUserId(userId);
        List<Goods> list = goodsService.findAllByShopId(shop.getId());

        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="查询，按brand名称")
    @GetMapping("/all/brand/{name}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllByBrandName")
    public Result findAllByBrandName(@PathVariable("name") String name){

        Brand brand = brandService.findOneByName(name);
        List<Goods> list = goodsService.findAllByBrandId(brand.getId());

        return Result.getInstance(200,"success").put("list",list);

    }

    @ApiOperation(value="查询，按brand名称")
    @GetMapping("/all/shop/{id}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllByShopId")
    public Result findAllByShopId(@PathVariable("id") Long id){
        List<Goods> list = goodsService.findAllByShopId(id);
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="查询，按brand名称")
    @GetMapping("/all/type/{name}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllByTypeName")
    public Result findAllByTypeName(@PathVariable("name") String name){

        Type type = typeService.findOneByName(name);
        List<Goods> list = goodsService.findAllByTypeId(type.getId());
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="模糊查询，按name")
    @GetMapping("/dimByName/{name}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findDimAllByName")
    public Result  findDimAllByName(@PathVariable("name") String name){
        List<Goods> list =goodsService.findDimAllByName("%"+name+"%");
        if(list==null){
            return Result.getInstance(505,"该商品不存在").put("list",null);
        }
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="模糊查询，按name",notes = "必需字段：pageIndex(起始页)，pageSize(每页大小)")
    @GetMapping("/page/name/{name}/{pageIndex}/{pageSize}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findPageByName")
    public Result  findPageByName(@PathVariable String name, @PathVariable Integer pageIndex, @PathVariable Integer pageSize) throws IOException {
        List<Goods> list=goodsService.findPageByName(name,pageIndex,pageSize);
        return Result.getInstance(200,"success").put("list",list);
    }


    @ApiOperation(value="获取所有特殊商品，该商品主要是放在首页展示",
            notes = "返回的结果有newList，hotList，recommendList三个集合，分别对应最新产品，热门产品，推荐产品")
    @GetMapping("/goodsSpecial/all")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllSpecial")
    public Result  findAllSpecial(){
        return goodsService.findAllSpecial();
    }


    @ApiOperation(value="查询特殊商品，按id")
    @GetMapping("/goodsSpecial/{id}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findOneSpecialById",exceptionsToIgnore = LogicException.class)
    public Result  findOneSpecialById(@PathVariable("id") Long id){

        Goods goods=goodsService.findSpecialOneById(id);
        if(goods==null){
            throw new LogicException("该商品不存在");
        }
        List<Goods> list=new ArrayList<>();
        list.add(goods);
        return Result.getInstance(200,"success").put("list",list);
    }


    @ApiOperation(value="获取某类特殊商品",
            notes = "返回的结果为newList，hotList，recommendList三个集合之一，分别对应最新产品，热门产品，推荐产品，其中kind的值只能为 '最新产品','热门产品','推荐产品'")
    @GetMapping("/goodsSpecial/kind/{kind}")
    @PermitAll
    @SentinelResource(value ="GoodsController.findAllSpecialByKind")
    public Result findAllSpecialByKind(@PathVariable("kind") String kind){
        List list=goodsService.findAllSpecialByKind(kind);
        return Result.getInstance(200,"success").
                put("list",list);
    }


    @ApiOperation(value="添加特殊商品，该商品会放在首页展示")
    @PostMapping("/goodsSpecial")
    @PreAuthorize("hasAuthority('goodsSuper')")
    @SentinelResource(value ="GoodsController.addSpecialOne")
    public Result addSpecialOne(@RequestBody(required = false) GoodsSpecial goodsSpecial) throws LogicException {
        //判断特殊是否存在
        if(!GoodsKind.search(goodsSpecial.getKind())){
            return Result.getInstance(505,"没有该产品种类");
        }
        Long flag = goodsService.addSpecialOne(goodsSpecial);
        if(flag==0){
            throw new LogicException("添加失败");
        }
        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="删除特殊商品")
    @DeleteMapping("/goodsSpecial/{id}")
    @PreAuthorize("hasAuthority('goodsSuper')")
    @SentinelResource(value ="GoodsController.deleteOneSpecialById")
    public Result deleteOneSpecialById(@PathVariable Long id) throws LogicException {

        Integer flag = goodsService.deleteOneSpecialById(id);
        if(flag==0){
            throw new LogicException("删除失败，该商品已不存在");
        }
        return Result.getInstance(200,"success");
    }


    @ApiOperation(value="修改",notes = "可选字段：name,place,price,number,brandId,typeId,introduce")
    @PutMapping("/repertory/{idNumbers}")
    //@PreAuthorize("hasAuthority('goodsSuper')")
    //@SentinelResource(value ="GoodsController.updateOne")
    public Result updateAllRepertory(@PathVariable("idNumbers") String idNumbers) throws Exception {

        System.out.println("enter goods");
        int i = goodsService.updateAllRepertory(Repertory.resolve(idNumbers));


        System.out.println(i);
        return Result.getInstance(200,"success");
    }

}
